package com.tywj.panda.user.details

import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.tywj.lib.core.common.extension.gone
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.extension.visible
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.route.RouteParam
import com.tywj.lib.route.RouteUtil
import com.tywj.panda.customer.common.api.CommonApi
import com.tywj.panda.customer.common.constant.GlobalCode
import com.tywj.panda.customer.common.entity.PayOrderDetailsEntity
import com.tywj.panda.customer.common.entity.TravelEntity
import com.tywj.panda.customer.common.http.PDObjectCallback
import com.tywj.panda.customer.common.provider.IH5Service
import com.tywj.panda.customer.common.provider.IPayService
import com.tywj.panda.customer.common.provider.ITravelService
import com.tywj.panda.customer.common.tool.MoneyTool
import com.tywj.panda.customer.common.view.base.MyBaseActivity
import com.tywj.panda.user.R
import com.tywj.panda.user.api.UserApi
import com.tywj.panda.user.route.UserRoute
import kotlinx.android.synthetic.main.user_activity_order_details.*

@Route(path = UserRoute.USER_ORDER_DETAILS)
class UserOrderDetailsActivity : MyBaseActivity() {

    override fun getLayoutID(): Int = R.layout.user_activity_order_details

    companion object {
        const val PARAMS_ID = "orderNo"
    }

    private var orderNo = ""

    private var payFee = 0

    private var orderDetailEntity: PayOrderDetailsEntity? = null

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)
        orderNo = RouteParam(this).getString(PARAMS_ID)
    }


    override fun initListener() {
        super.initListener()

        btnTicketTransfer.onClick {
            shortToast("去转让")
        }
        tvRefundRule.onClick {

            RouteUtil.getServiceProvider(IH5Service::class.java)
                ?.toH5Activity(
                    indexUrl = CommonApi.H5_URL + "pages/refund/refund",
                    title = "退改规则",
                    titleBgColor = ResourcesUtil.getColor(com.tywj.panda.customer.usercenter.R.color.common_black_1F),
                    isShowCloseView = false
                )?.navigation(this)
        }

        //支付
        btnPay.onClick {
            toPay(orderNo, payFee)
        }

        statusLayout.setOnEmptyLayoutButtonClick {
            loadData(orderNo)
        }

        statusLayout.setOnErrorLayoutButtonClick {
            loadData(orderNo)
        }

        //选择票后跳到相应的行程
        ticketDetailsPrice.setSelectedData { goods ->

            //拼接行程的数据
            orderDetailEntity?.let {
                val bean = TravelEntity.DataBean()
                //为防止服务器不遵守约定的null值处理
                bean.lineName = it.lineName ?: ""
                bean.startStation = it.startStation ?: ""
                bean.endStation = it.endStation ?: ""
                bean.offTime = it.offTime ?: ""
                bean.onTime = it.onTime ?: ""
                bean.lineCode = it.lineCode ?: ""

                bean.lineTime = it.lineTime ?: ""
                bean.lineDate = goods.lineDate ?: ""
                bean.number = goods.number ?: 1
                bean.price = goods.price ?: 0

                bean.status = goods.status ?: 0
                bean.goodsNo = goods.goodsNo ?: ""
                bean.vehicleNo = goods.vehicleNo ?: ""
                bean.ticketCode = goods.ticketCode ?: ""

                RouteUtil.getServiceProvider(ITravelService::class.java)?.toTravelDetails(bean)
                    ?.navigation(this)
            }
        }

    }

    override fun loadDataOnCreate() {
        super.loadDataOnCreate()

        loadData(orderNo)
    }

    private fun loadData(orderNo: String) {
        statusLayout.showLoadingLayout()
        UserApi.getOrderDetail(orderNo).attachToLifecycle(this)
            .execute(object : PDObjectCallback<PayOrderDetailsEntity>(PayOrderDetailsEntity::class.java) {
                override fun success(data: PayOrderDetailsEntity) {
                    statusLayout.showContentLayout()
                    handleData(data)
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    gone(flWaitPay)
                    statusLayout.showErrorLayoutByCode(code, message)
                }
            })
    }

    private fun handleData(data: PayOrderDetailsEntity) {
        orderDetailEntity = data

        payFee = data.orderFee

        tvNumber.text = data.number.toString()
        tvBusLineName.text = data.lineName
        tvStartPoint.text = data.startStation
        tvEndPoint.text = data.endStation
        tvOrderNo.text = data.orderNo
        tvOrderTime.text = data.orderTime
        tvTime.text = data.lineTime
        tvPayTime.text = data.payTime
        tvDiscountPrice.text = MoneyTool.formatFen(data.refundFee)
        tvPayMoney.text = MoneyTool.formatFen(payFee)
        tvTotalMoney.text = MoneyTool.formatFen(payFee)
        tvActPay.text = MoneyTool.formatFen(payFee)

        //需要根据支付状态判断
        getOrderStatus(data.orderStatus)

        //设置日历显示
        ticketDetailsPrice.loadDatePrice(this, data.calender)
    }


    private fun getOrderStatus(orderStatus: Int) {
        when (orderStatus) {
            GlobalCode.ORDER_STATUS_ALL -> {
                tvOrderStatus.text = "待付款"
                //支付时间、实付金额、退款规则
                gone(flPayTime, flActPrice, tvRefundRule)

                //显示支付
                visible(flWaitPay)

            }
            GlobalCode.ORDER_STATUS_MADE_PAYMENT -> {
                tvOrderStatus.text = "已付款"

                visible(flPayTime, flActPrice, tvRefundRule)
                gone(flWaitPay)
            }
            GlobalCode.ORDER_STATUS_REFUND -> {
                tvOrderStatus.text = "已退款"

                visible(flPayTime, tvRefundRule)
                gone(flWaitPay, flActPrice)
            }
            GlobalCode.ORDER_STATUS_CANCELED -> {
                tvOrderStatus.text = "已取消"
                gone(flPayTime, flWaitPay, flActPrice)
            }
            GlobalCode.ORDER_STATUS_EXPIRED -> {
                tvOrderStatus.text = "已过期"
                gone(flWaitPay, flActPrice)
            }
            GlobalCode.ORDER_STATUS_PAY_FAILED -> {
                tvOrderStatus.text = "支付失败"

                visible(flWaitPay)
                gone(flActPrice)
            }
            GlobalCode.ORDER_STATUS_COMPLETED -> {
                tvOrderStatus.text = "已完成"

                visible(flPayTime, flActPrice)
                gone(flWaitPay)
            }
            else -> {
                tvOrderStatus.text = "未定义"
                gone(flWaitPay)
            }
        }
    }

    private fun toPay(orderNo: String, payFee: Int) {

        RouteUtil.getServiceProvider(IPayService::class.java)?.toPay(orderNo, payFee, object : IPayService.Callback {
            override fun onPayResult(clickType: Int) {
                handlePayResult(orderNo, clickType)
            }
        })?.navigation(this)
    }

    //支付成功后到详情页刷新，其他情况只是返回处理即可
    private fun handlePayResult(orderNo: String, clickType: Int) {
        when (clickType) {
            IPayService.CLICK_PAY_SUCCESS_DETAIL -> {
                loadData(orderNo)
            }
            IPayService.CLICK_PAY_SUCCESS_CLOSE -> {
            }
            IPayService.CLICK_PAY_FAIL_CLOSE -> {
            }
            IPayService.CLICK_CHOOSE_PAY_CLOSE -> {
            }
            else -> {
            }
        }
    }
}